package db

import (
	"errors"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"os"
	"path/filepath"
)

var supportType = struct {
	Sqlite, Mysql, Pgsql string
}{
	Sqlite: "sqlite",
	Mysql:  "mysql",
	Pgsql:  "pgsql",
}

func GetDB(supper string, showSql bool, source string, appPath string) (db *gorm.DB, err error) {
	var logMode logger.Interface
	// 只有当日志级别时debug时才打印sql，
	if showSql {
		logMode = logger.Default.LogMode(logger.Info)
	} else {
		logMode = logger.Default.LogMode(logger.Silent)
	}
	switch supper {
	case supportType.Sqlite:
		if appPath == "" {
			appPath, err = os.Executable()
			if err != nil {
				return
			}
		}
		if !IsFolderExist(filepath.Join(appPath, "data")) {
			err = os.MkdirAll(filepath.Join(appPath, "data"), 0777)
			if err != nil {
				return nil, err
			}
		}
		db, err = gorm.Open(sqlite.Open(filepath.Join(appPath, "data", source)), &gorm.Config{
			Logger: logMode,
		})
	case supportType.Mysql:
		db, err = gorm.Open(mysql.Open(source), &gorm.Config{
			Logger: logMode,
		})
	case supportType.Pgsql:
		db, err = gorm.Open(postgres.Open(source), &gorm.Config{
			Logger: logMode,
		})
	default:
		err = errors.New("未定义的数据库类型")
	}
	return db, err
}

// IsFolderExist 判断文件夹是否存在
func IsFolderExist(folderPath string) bool {
	fileInfo, err := os.Stat(folderPath)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return fileInfo.IsDir()
}
